<template>
  <div class="labeler-daily-output-page">
    <!-- 标签页 -->
    <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
      <el-tab-pane label="产值记录" name="dailyOutput">
        <div class="page-header">
          <h2>标注员每日产值记录</h2>
          <el-button type="primary" @click="showAddDialog">新增记录</el-button>
        </div>

        <!-- 查询条件 -->
        <div class="query-area">
          <el-form :model="queryForm" inline size="small">
            <el-form-item label="记录日期">
              <el-date-picker
                v-model="queryForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 220px;"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="标注员姓名">
              <el-input
                v-model="queryForm.labelerName"
                placeholder="请输入标注员姓名"
                clearable
                style="width: 150px;"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button @click="exportData">导出</el-button>
              <el-button @click="downloadTemplate">下载模板</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 数据表格 -->
        <div class="table-area">
          <el-table
            :data="tableData"
            border
            stripe
            v-loading="tableLoading"
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <el-table-column prop="labelerName" label="标注员姓名" width="120" align="center"></el-table-column>
            <el-table-column prop="recordDate" label="记录日期" width="120" align="center">
              <template slot-scope="scope">
                {{ scope.row.recordDate | formatDate }}
              </template>
            </el-table-column>
            <el-table-column prop="targetBoxCount" label="应达到框数" width="120" align="center"></el-table-column>
            <el-table-column prop="actualBoxCount" label="实际框数" width="120" align="center"></el-table-column>
            <el-table-column prop="completionRate" label="完成率" width="100" align="center">
              <template slot-scope="scope">
                {{ calculateCompletionRate(scope.row.actualBoxCount, scope.row.targetBoxCount) }}
              </template>
            </el-table-column>
            <el-table-column prop="uncompletedReason" label="未完成原因" min-width="200" align="center"></el-table-column>
            <!-- <el-table-column prop="createTime" label="创建时间" width="180" align="center">
              <template slot-scope="scope">
                {{ scope.row.createTime | formatDate }}
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="150" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="text" size="small" style="color: #f56c6c" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            style="margin-top: 20px; text-align: right"
          >
          </el-pagination>
        </div>

        <!-- 图表区域 -->
        <div class="chart-area">
          <h3>标注员实际框数统计图</h3>
          <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          width="600px"
          :close-on-click-modal="false"
        >
          <el-form
            ref="outputForm"
            :model="formData"
            :rules="formRules"
            label-width="120px"
          >
            <el-form-item label="标注员姓名" prop="labelerName">
              <el-select
                v-model="formData.labelerName"
                filterable
                placeholder="请选择标注员姓名"
                style="width: 100%"
                @change="handleLabelerChange"
              >
                <el-option
                  v-for="item in labelerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                  :data-id="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="记录日期" prop="recordDate">
              <el-date-picker
                v-model="formData.recordDate"
                type="date"
                placeholder="请选择记录日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="应达到框数" prop="targetBoxCount">
              <el-input-number
                v-model="formData.targetBoxCount"
                :min="0"
                placeholder="请输入应达到框数"
                style="width: 100%"
                @change="handleBoxCountChange"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="实际框数" prop="actualBoxCount">
              <el-input-number
                v-model="formData.actualBoxCount"
                :min="0"
                placeholder="请输入实际框数"
                style="width: 100%"
                @change="handleBoxCountChange"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="未完成原因" prop="uncompletedReason">
              <el-input
                v-model="formData.uncompletedReason"
                type="textarea"
                :rows="3"
                placeholder="请输入未完成原因（如已完成则留空）"
              ></el-input>
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
          </div>
        </el-dialog>

        <!-- Excel批量导入区域 -->
        <div class="batch-import-area">
          <div class="import-header">
            <h3>Excel批量导入</h3>
            <el-button type="primary" size="small" @click="downloadTemplate">
              <i class="el-icon-download"></i> 下载导入模板
            </el-button>
          </div>
          
          <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :limit="1"
            accept=".xlsx,.xls"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只支持.xlsx或.xls格式的Excel文件，文件大小不超过10MB</div>
          </el-upload>
          
          <!-- 文件预览区域 -->
          <div v-if="selectedFile" class="file-preview">
            <div class="preview-header">
              <i class="el-icon-document"></i>
              <span class="file-name">{{ selectedFile.name }}</span>
              <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
              <el-button 
                type="danger" 
                size="mini" 
                icon="el-icon-delete" 
                circle 
                @click="removeFile"
                title="删除文件"
              ></el-button>
            </div>
            <div class="preview-info">
              <p><i class="el-icon-info"></i> 文件已选择，点击"批量导入"按钮开始导入</p>
            </div>
          </div>
          
          <!-- 进度条 -->
          <el-progress 
            v-if="importLoading" 
            :percentage="importProgress" 
            :show-text="true" 
            style="margin-top: 10px;"
          ></el-progress>
          
          <el-button 
            type="success" 
            style="margin-top: 10px;" 
            @click="handleImport"
            :loading="importLoading"
            :disabled="!selectedFile"
          >
            <i class="el-icon-upload2"></i> {{ importLoading ? '导入中...' : '批量导入' }}
          </el-button>
        </div>
        
        <!-- 导入结果对话框 -->
        <el-dialog
          title="导入结果"
          :visible.sync="importResultVisible"
          width="600px"
          :close-on-click-modal="false"
        >
          <el-table :data="[importResult]" border style="width: 100%">
            <el-table-column prop="totalRows" label="总记录数" width="100" align="center"></el-table-column>
            <el-table-column prop="successRows" label="成功记录数" width="100" align="center">
              <template slot-scope="scope">
                <span style="color: #67c23a">{{ scope.row.successRows }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="failRows" label="失败记录数" width="100" align="center">
              <template slot-scope="scope">
                <span style="color: #f56c6c">{{ scope.row.failRows }}</span>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="importResult.errorMessages && importResult.errorMessages.length > 0" style="margin-top: 20px;">
            <h4>错误信息：</h4>
            <el-table :data="importResult.errorMessages.slice(0, 10)" border max-height="300">
              <el-table-column prop="rowNumber" label="行号" width="80" align="center"></el-table-column>
              <el-table-column prop="errorMessage" label="错误信息" min-width="300"></el-table-column>
            </el-table>
            <p v-if="importResult.errorMessages.length > 10" style="color: #909399; margin-top: 10px;">
              仅显示前10条错误信息，共{{ importResult.errorMessages.length }}条错误
            </p>
          </div>
          
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="importResultVisible = false">确定</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
      
      <!-- 提包领取及完成情况标签页 -->
      <el-tab-pane label="提包领取及完成情况" name="taskPackage">
        <div class="page-header">
          <h2>提包领取及完成情况</h2>
          <el-button type="primary" @click="showAddPackageDialog">新增记录</el-button>
        </div>

        <!-- 查询条件 -->
        <div class="query-area">
          <el-form :model="packageQueryForm" inline size="small">
            <el-form-item label="领取时间">
              <el-date-picker
                v-model="packageQueryForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 220px;"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="标注员姓名">
              <el-input
                v-model="packageQueryForm.labelerName"
                placeholder="请输入标注员姓名"
                clearable
                style="width: 150px;"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="packageQueryForm.status" placeholder="请选择状态" clearable style="width: 120px;">
                <el-option label="进行中" value="进行中"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
                <el-option label="已返修" value="已返修"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handlePackageQuery">查询</el-button>
              <el-button @click="handlePackageReset">重置</el-button>
              <el-button @click="exportPackageData">导出</el-button>
              <el-button @click="downloadPackageTemplate">下载模板</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 数据表格 -->
        <div class="table-area">
          <el-table
            :data="packageTableData"
            border
            stripe
            v-loading="packageTableLoading"
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <el-table-column prop="labelerName" label="姓名" width="120" align="center"></el-table-column>
            <el-table-column prop="receiveTime" label="领取时间" width="160" align="center">
              <template slot-scope="scope">
                {{ scope.row.receiveTime }}
              </template>
            </el-table-column>
            <el-table-column prop="account" label="账号" width="120" align="center"></el-table-column>
            <el-table-column prop="taskBatch" label="任务批次" width="120" align="center"></el-table-column>
            <el-table-column prop="packageId" label="提包Id" width="120" align="center"></el-table-column>
            <el-table-column prop="deliveryTime" label="交付时间" width="160" align="center">
              <template slot-scope="scope">
                {{ scope.row.deliveryTime }}
              </template>
            </el-table-column>
            <el-table-column prop="deliveryBoxCount" label="交付框数" width="100" align="center"></el-table-column>
            <el-table-column prop="repairCount" label="返修次数" width="100" align="center"></el-table-column>
            <el-table-column prop="finalBoxCount" label="最终框数" width="100" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template slot-scope="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleEditPackage(scope.row)">编辑</el-button>
                <el-button type="text" size="small" style="color: #f56c6c" @click="handleDeletePackage(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @size-change="handlePackageSizeChange"
            @current-change="handlePackageCurrentChange"
            :current-page="packagePagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="packagePagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="packagePagination.total"
            style="margin-top: 20px; text-align: right"
          >
          </el-pagination>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog
          :title="packageDialogTitle"
          :visible.sync="packageDialogVisible"
          width="600px"
          :close-on-click-modal="false"
        >
          <el-form
            ref="packageForm"
            :model="packageFormData"
            :rules="packageFormRules"
            label-width="120px"
          >
            <el-form-item label="姓名" prop="labelerName">
              <el-select
                v-model="packageFormData.labelerName"
                filterable
                placeholder="请选择标注员姓名"
                style="width: 100%"
              >
                <el-option
                  v-for="item in labelerList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="领取时间" prop="receiveTime">
              <el-date-picker
                v-model="packageFormData.receiveTime"
                type="datetime"
                placeholder="请选择领取时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="账号" prop="account">
              <el-input
                v-model="packageFormData.account"
                placeholder="请输入账号"
              ></el-input>
            </el-form-item>

            <el-form-item label="任务批次" prop="taskBatch">
              <el-input
                v-model="packageFormData.taskBatch"
                placeholder="请输入任务批次"
              ></el-input>
            </el-form-item>

            <el-form-item label="提包Id" prop="packageId">
              <el-input
                v-model="packageFormData.packageId"
                placeholder="请输入提包Id"
              ></el-input>
            </el-form-item>

            <el-form-item label="交付时间" prop="deliveryTime">
              <el-date-picker
                v-model="packageFormData.deliveryTime"
                type="datetime"
                placeholder="请选择交付时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="交付框数" prop="deliveryBoxCount">
              <el-input-number
                v-model="packageFormData.deliveryBoxCount"
                :min="0"
                placeholder="请输入交付框数"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="返修次数" prop="repairCount">
              <el-input-number
                v-model="packageFormData.repairCount"
                :min="0"
                placeholder="请输入返修次数"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="最终框数" prop="finalBoxCount">
              <el-input-number
                v-model="packageFormData.finalBoxCount"
                :min="0"
                placeholder="请输入最终框数"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select v-model="packageFormData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="进行中" value="进行中"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
                <el-option label="已返修" value="已返修"></el-option>
              </el-select>
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="packageDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handlePackageSubmit" :loading="packageSubmitLoading">确定</el-button>
          </div>
        </el-dialog>

        <!-- Excel批量导入区域 -->
        <div class="batch-import-area">
          <div class="import-header">
            <h3>Excel批量导入</h3>
            <el-button type="primary" size="small" @click="downloadPackageTemplate">
              <i class="el-icon-download"></i> 下载导入模板
            </el-button>
          </div>
          
          <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :on-change="handlePackageFileChange"
            :on-remove="handlePackageFileRemove"
            :file-list="packageFileList"
            :limit="1"
            accept=".xlsx,.xls"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只支持.xlsx或.xls格式的Excel文件，文件大小不超过10MB</div>
          </el-upload>
          
          <!-- 文件预览区域 -->
          <div v-if="selectedPackageFile" class="file-preview">
            <div class="preview-header">
              <i class="el-icon-document"></i>
              <span class="file-name">{{ selectedPackageFile.name }}</span>
              <span class="file-size">({{ formatFileSize(selectedPackageFile.size) }})</span>
              <el-button 
                type="danger" 
                size="mini" 
                icon="el-icon-delete" 
                circle 
                @click="removePackageFile"
                title="删除文件"
              ></el-button>
            </div>
            <div class="preview-info">
              <p><i class="el-icon-info"></i> 文件已选择，点击"批量导入"按钮开始导入</p>
            </div>
          </div>
          
          <!-- 进度条 -->
          <el-progress 
            v-if="packageImportLoading" 
            :percentage="packageImportProgress" 
            :show-text="true" 
            style="margin-top: 10px;"
          ></el-progress>
          
          <el-button 
            type="success" 
            style="margin-top: 10px;" 
            @click="handlePackageImport"
            :loading="packageImportLoading"
            :disabled="!selectedPackageFile"
          >
            <i class="el-icon-upload2"></i> {{ packageImportLoading ? '导入中...' : '批量导入' }}
          </el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { 
  getLabelerDailyOutputListAPI, 
  addLabelerDailyOutputAPI, 
  updateLabelerDailyOutputAPI, 
  deleteLabelerDailyOutputAPI,
  getLabelerDailyOutputChartDataAPI,
  downloadImportTemplateAPI,
  importLabelerDailyOutputAPI,
  exportLabelerDailyOutputAPI
} from '@/api/labelerDailyOutput';
import { getLabelerListAPI } from '@/api/labeler';
import {
  getLabelerTaskPackageListAPI,
  addLabelerTaskPackageAPI,
  updateLabelerTaskPackageAPI,
  deleteLabelerTaskPackageAPI,
  downloadTaskPackageTemplateAPI,
  importLabelerTaskPackageAPI,
  exportLabelerTaskPackageAPI
} from '@/api/labelerTaskPackage';
import * as echarts from 'echarts';

export default {
  name: 'LabelerDailyOutput',
  filters: {
    // 格式化日期
    formatDate(value) {
      if (!value) return '';
      return value.substring(0, 19);
    }
  },
  data() {
    return {
      activeTab: 'dailyOutput', // 默认激活的标签页
      dialogVisible: false,
      dialogTitle: '新增记录',
      submitLoading: false,
      packageDialogVisible: false,
      packageDialogTitle: '新增记录',
      packageSubmitLoading: false,
      // 查询表单
      queryForm: {
        dateRange: null,
        labelerName: ''
      },
      packageQueryForm: {
        dateRange: null,
        labelerName: '',
        status: ''
      },
      // 表格数据
      tableData: [],
      tableLoading: false,
      packageTableData: [],
      packageTableLoading: false,
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      packagePagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 表单数据
      formData: {
        labelerId: null,
        labelerName: '',
        recordDate: '',
        targetBoxCount: 0,
        actualBoxCount: 0,
        uncompletedReason: ''
      },
      formRules: {
        labelerName: [
          { required: true, message: '请选择标注员姓名', trigger: 'change' }
        ],
        recordDate: [
          { required: true, message: '请选择记录日期', trigger: 'change' }
        ],
        targetBoxCount: [
          { required: true, message: '请输入应达到框数', trigger: 'blur' }
        ],
        actualBoxCount: [
          { required: true, message: '请输入实际框数', trigger: 'blur' }
        ],
        uncompletedReason: [
          { 
            required: true, 
            message: '请输入未完成原因', 
            trigger: 'blur',
            validator: (rule, value, callback) => {
              // 只有当应到达框数大于实际框数时才需要输入未完成原因
              if (this.formData.targetBoxCount > this.formData.actualBoxCount) {
                if (!value || value.trim() === '') {
                  callback(new Error('请输入未完成原因'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }
          }
        ]
      },
      packageFormData: {
        labelerName: '',
        receiveTime: '',
        account: '',
        taskBatch: '',
        packageId: '',
        deliveryTime: '',
        deliveryBoxCount: 0,
        repairCount: 0,
        finalBoxCount: 0,
        status: '进行中'
      },
      packageFormRules: {
        labelerName: [
          { required: true, message: '请选择标注员姓名', trigger: 'change' }
        ],
        receiveTime: [
          { required: true, message: '请选择领取时间', trigger: 'change' }
        ],
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        taskBatch: [
          { required: true, message: '请输入任务批次', trigger: 'blur' }
        ],
        packageId: [
          { required: true, message: '请输入提包Id', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      // 标注员列表
      labelerList: [],
      // 图表实例
      chartInstance: null,
      // Excel导入相关
      selectedFile: null,
      fileList: [],  // 文件列表
      importLoading: false,
      importProgress: 0,  // 导入进度
      selectedPackageFile: null,
      packageFileList: [],  // 文件列表
      packageImportLoading: false,
      packageImportProgress: 0,  // 导入进度
      importResultVisible: false,
      importResult: {
        totalRows: 0,
        successRows: 0,
        failRows: 0,
        errorMessages: []
      }
    };
  },
  mounted() {
    // 页面加载时查询数据
    this.getTableData();
    // 初始化图表
    this.initChart();
    // 获取图表数据
    this.getChartData();
    
    // 获取任务包数据
    this.getPackageTableData();
    
    // 获取所有标注员列表
    this.getAllLabelers();
  },
  methods: {
    // 计算完成率
    calculateCompletionRate(actualBoxCount, targetBoxCount) {
      // 避免除以零的情况
      if (!targetBoxCount || targetBoxCount === 0) {
        return '0.00%';
      }
      // 计算完成率并保留两位小数
      const rate = (actualBoxCount / targetBoxCount) * 100;
      return rate.toFixed(2) + '%';
    },
    
    // 获取所有标注员列表
    getAllLabelers() {
      // 构建查询参数，获取所有标注员
      const params = {
        currentPage: 1,
        pageSize: 1000  // 获取足够多的数据
      };
      
      // 调用后端接口查询标注员列表
      getLabelerListAPI(params).then(res => {
        if (res.code === 200) {
          // 将返回的记录赋值给labelerList
          this.labelerList = res.data.records || [];
        } else {
          this.$message.error(res.message || '查询标注员失败');
          this.labelerList = [];
        }
      }).catch(error => {
        this.$message.error('查询标注员失败，请检查网络');
        console.error('查询标注员错误:', error);
        this.labelerList = [];
      });
    },
    
    // 标签页切换
    handleTabClick(tab) {
      if (tab.name === 'taskPackage') {
        this.getPackageTableData();
      }
    },
    
    // 查询数据
    handleQuery() {
      this.pagination.currentPage = 1;
      this.getTableData();
      // 同时更新图表数据
      this.getChartData();
    },
    
    // 重置查询
    handleReset() {
      this.queryForm = {
        dateRange: null,
        labelerName: ''
      };
      this.pagination.currentPage = 1;
      this.getTableData();
      // 同时更新图表数据
      this.getChartData();
    },
    
    // 导出数据
    exportData() {
      // 构建查询参数
      const params = {};
      
      if (this.queryForm.dateRange && this.queryForm.dateRange.length === 2) {
        params.startDate = this.queryForm.dateRange[0];
        params.endDate = this.queryForm.dateRange[1];
      }
      
      if (this.queryForm.labelerName) {
        params.labelerName = this.queryForm.labelerName;
      }
      
      this.$message.info('正在导出数据，请稍候...');
      
      // 调用导出接口
      exportLabelerDailyOutputAPI(params).then(res => {
        console.log('导出',res)
        if (res ) {
          // 创建下载链接
          const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = '标注员产值记录.xlsx';
          link.click();
          window.URL.revokeObjectURL(url);
          this.$message.success('导出成功');
        } else {
          this.$message.error('导出失败');
        }
      }).catch(error => {
        this.$message.error('导出失败，请检查网络');
        console.error('导出错误:', error);
      });
    },
    
    // 下载模板
    downloadTemplate() {
      this.$message.info('正在下载模板...');
      downloadImportTemplateAPI().then(res => {
        // 创建下载链接
        const blob = new Blob([res], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = '标注员产值记录导入模板.xlsx';
        link.click();
        window.URL.revokeObjectURL(url);
        this.$message.success('模板下载成功');
      }).catch(error => {
        this.$message.error('模板下载失败');
        console.error('下载错误:', error);
      });
    },
    
    // 处理文件上传
    handleFileChange(file, fileList) {
      // 验证文件类型
      const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                   || file.raw.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件！');
        // 移除非法文件
        this.fileList = [];
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB！');
        // 移除超大文件
        this.fileList = [];
        return false;
      }
      
      this.selectedFile = file.raw;
      this.fileList = [file];
      
      // 选择文件后自动开始导入
      // this.handleImport();
    },
    
    // 删除文件（通过上传组件的删除按钮）
    handleFileRemove(file, fileList) {
      this.selectedFile = null;
      this.fileList = [];
      this.$message.info('文件已移除');
    },
    
    // 手动删除文件
    removeFile() {
      this.selectedFile = null;
      this.fileList = [];
      this.$message.info('文件已移除，可以重新上传');
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    },
    
    // 批量导入
    handleImport() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择要导入的Excel文件');
        return;
      }
      
      this.importLoading = true;
      this.importProgress = 0;
      this.$message.info('正在导入数据，请稍候...');
      
      // 创建进度更新函数
      const updateProgress = (progressEvent) => {
        if (progressEvent.percent) {
          this.importProgress = Math.round(progressEvent.percent);
        }
      };
      
      importLabelerDailyOutputAPI(this.selectedFile, { onProgress: updateProgress }).then(res => {
        this.importLoading = false;
        // 检查响应数据结构
        if (res && res.code === 200) {
          // 更新导入结果数据
          const resultData = res.data || {};
          this.importResult = {
            totalRows: resultData.totalRows || 0,
            successRows: resultData.successRows || 0,
            failRows: resultData.failRows || 0,
            errorMessages: resultData.errorMessages || []
          };
          
          // 根据导入结果给出相应提示
          if (this.importResult.failRows === 0) {
            this.$message.success(`导入完成！成功导入${this.importResult.successRows}条数据`);
          } else {
            this.$message.warning(`导入完成！成功${this.importResult.successRows}条，失败${this.importResult.failRows}条`);
          }
          
          // 导入成功后刷新列表和图表
          this.getTableData();
          this.getChartData();
          
          // 清空文件选择
          this.selectedFile = null;
          this.fileList = [];
        } else {
          this.$message.error(res.message || '导入失败');
        }
      }).catch(error => {
        this.importLoading = false;
        this.$message.error('导入失败，请检查网络或文件格式');
        console.error('导入错误:', error);
      });
    },
    
    // 获取表格数据
    getTableData() {
      this.tableLoading = true;
      
      // 构建查询参数
      const params = {
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      };
      
      if (this.queryForm.dateRange && this.queryForm.dateRange.length === 2) {
        params.startDate = this.queryForm.dateRange[0];
        params.endDate = this.queryForm.dateRange[1];
      }
      
      if (this.queryForm.labelerName) {
        params.labelerName = this.queryForm.labelerName;
      }
      
      // 调用后端接口查询数据
      getLabelerDailyOutputListAPI(params).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.pagination.total = res.data.total || 0;
          this.pagination.currentPage = res.data.currentPage || 1;
          this.pagination.pageSize = res.data.pageSize || 10;
        } else {
          this.$message.error(res.message || '查询失败');
        }
      }).catch(error => {
        this.tableLoading = false;
        this.$message.error('查询失败，请检查网络');
        console.error('查询错误:', error);
      });
    },
    
    // 获取图表数据
    getChartData() {
      // 构建查询参数
      const params = {};
      
      if (this.queryForm.dateRange && this.queryForm.dateRange.length === 2) {
        params.startDate = this.queryForm.dateRange[0];
        params.endDate = this.queryForm.dateRange[1];
      }
      
      // 调用后端接口获取图表数据
      getLabelerDailyOutputChartDataAPI(params).then(res => {
        if (res.code === 200) {
          this.updateChart(res.data);
        } else {
          this.$message.error(res.message || '图表数据获取失败');
        }
      }).catch(error => {
        this.$message.error('图表数据获取失败，请检查网络');
        console.error('图表数据获取错误:', error);
      });
    },
    
    // 初始化图表
    initChart() {
      this.$nextTick(() => {
        if (this.$refs.chartContainer) {
          this.chartInstance = echarts.init(this.$refs.chartContainer);
          // 设置初始图表配置
          const option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            xAxis: {
              type: 'category',
              data: []
            },
            yAxis: {
              type: 'value',
              name: '实际框数'
            },
            series: [{
              data: [],
              type: 'bar',
              barWidth: '60%',
              itemStyle: {
                color: '#409EFF'
              }
            }]
          };
          this.chartInstance.setOption(option);
        }
      });
    },
    
    // 更新图表数据
    updateChart(chartData) {
      if (this.chartInstance) {
        const option = {
          xAxis: {
            data: chartData.labelerNames
          },
          series: [{
            data: chartData.actualBoxCounts
          }]
        };
        this.chartInstance.setOption(option);
      }
    },
    
    // 搜索标注员
    searchLabelers(query) {
      // 构建查询参数
      const params = {
        currentPage: 1,
        pageSize: 10,
        name: query
      };
      
      // 调用后端接口查询标注员列表
      getLabelerListAPI(params).then(res => {
        if (res.code === 200) {
          // 将返回的记录赋值给labelerList
          this.labelerList = res.data.records || [];
        } else {
          this.$message.error(res.message || '查询标注员失败');
          this.labelerList = [];
        }
      }).catch(error => {
        this.$message.error('查询标注员失败，请检查网络');
        console.error('查询标注员错误:', error);
        this.labelerList = [];
      });
    },
    
    // 处理标注员选择变化
    handleLabelerChange(value) {
      // 根据选中的标注员姓名查找对应的ID
      const selectedLabeler = this.labelerList.find(item => item.name === value);
      if (selectedLabeler) {
        this.formData.labelerId = selectedLabeler.id;
      } else {
        this.formData.labelerId = null;
      }
    },
    
    // 处理框数变化
    handleBoxCountChange() {
      // 触发未完成原因字段的验证
      this.$refs.outputForm.validateField('uncompletedReason');
    },
    
    // 搜索任务包标注员
    searchPackageLabelers(query) {
      // 构建查询参数
      const params = {
        currentPage: 1,
        pageSize: 10,
        name: query
      };
      
      // 调用后端接口查询标注员列表
      getLabelerListAPI(params).then(res => {
        if (res.code === 200) {
          // 将返回的记录赋值给labelerList
          this.labelerList = res.data.records || [];
        } else {
          this.$message.error(res.message || '查询标注员失败');
          this.labelerList = [];
        }
      }).catch(error => {
        this.$message.error('查询标注员失败，请检查网络');
        console.error('查询标注员错误:', error);
        this.labelerList = [];
      });
    },
    
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑记录';
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端删除接口
        deleteLabelerDailyOutputAPI(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getTableData();
            // 同时更新图表数据
            this.getChartData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(error => {
          this.$message.error('删除失败，请检查网络');
          console.error('删除错误:', error);
        });
      }).catch(() => {});
    },
    
    // 分页 - 每页条数改变
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 分页 - 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getTableData();
    },
    
    // 显示新增对话框
    showAddDialog() {
      this.dialogTitle = '新增记录';
      this.resetForm();
      this.dialogVisible = true;
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        labelerId: null,
        labelerName: '',
        recordDate: '',
        targetBoxCount: 0,
        actualBoxCount: 0,
        uncompletedReason: ''
      };
      if (this.$refs.outputForm) {
        this.$refs.outputForm.resetFields();
      }
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.outputForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          
          // 添加当前登录用户的ID
          const currentUser = JSON.parse(localStorage.getItem('admin_user') || '{}');
          const submitData = {
            ...this.formData,
            userId: currentUser.id || null
          };
          
          // 判断是新增还是编辑
          const isEdit = !!this.formData.id;
          const apiCall = isEdit 
            ? updateLabelerDailyOutputAPI(this.formData.id, submitData)
            : addLabelerDailyOutputAPI(submitData);
          
          apiCall.then(res => {
            this.submitLoading = false;
            if (res.code === 200) {
              this.$message.success(isEdit ? '修改成功' : '新增成功');
              this.dialogVisible = false;
              this.resetForm();
              // 刷新列表
              this.getTableData();
              // 同时更新图表数据
              this.getChartData();
            } else {
              this.$message.error(res.message || '操作失败');
            }
          }).catch(error => {
            this.submitLoading = false;
            this.$message.error('操作失败，请检查网络');
            console.error('提交错误:', error);
          });
        }
      });
    },
    
    // 提包相关方法
    // 查询数据
    handlePackageQuery() {
      this.packagePagination.currentPage = 1;
      this.getPackageTableData();
    },
    
    // 重置查询
    handlePackageReset() {
      this.packageQueryForm = {
        dateRange: null,
        labelerName: '',
        status: ''
      };
      this.packagePagination.currentPage = 1;
      this.getPackageTableData();
    },
    
    // 导出数据
    exportPackageData() {
      // 构建查询参数
      const params = {};
      
      if (this.packageQueryForm.dateRange && this.packageQueryForm.dateRange.length === 2) {
        params.startDate = this.packageQueryForm.dateRange[0];
        params.endDate = this.packageQueryForm.dateRange[1];
      }
      
      if (this.packageQueryForm.labelerName) {
        params.labelerName = this.packageQueryForm.labelerName;
      }
      
      if (this.packageQueryForm.status) {
        params.status = this.packageQueryForm.status;
      }
      
      this.$message.info('正在导出数据，请稍候...');
      
      // 调用导出接口
      exportLabelerTaskPackageAPI(params).then(res => {
        if (res) {
          // 创建下载链接
          const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = '提包领取及完成情况.xlsx';
          link.click();
          window.URL.revokeObjectURL(url);
          this.$message.success('导出成功');
        } else {
          this.$message.error('导出失败');
        }
      }).catch(error => {
        this.$message.error('导出失败，请检查网络');
        console.error('导出错误:', error);
      });
    },
    
    // 下载模板
    downloadPackageTemplate() {
      this.$message.info('正在下载模板...');
      downloadTaskPackageTemplateAPI().then(res => {
        // 创建下载链接
        const blob = new Blob([res], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = '提包领取及完成情况导入模板.xlsx';
        link.click();
        window.URL.revokeObjectURL(url);
        this.$message.success('模板下载成功');
      }).catch(error => {
        this.$message.error('模板下载失败');
        console.error('下载错误:', error);
      });
    },
    
    // 处理文件上传
    handlePackageFileChange(file, fileList) {
      // 验证文件类型
      const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                   || file.raw.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件！');
        // 移除非法文件
        this.packageFileList = [];
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB！');
        // 移除超大文件
        this.packageFileList = [];
        return false;
      }
      
      this.selectedPackageFile = file.raw;
      this.packageFileList = [file];
    },
    
    // 删除文件（通过上传组件的删除按钮）
    handlePackageFileRemove(file, fileList) {
      this.selectedPackageFile = null;
      this.packageFileList = [];
      this.$message.info('文件已移除');
    },
    
    // 手动删除文件
    removePackageFile() {
      this.selectedPackageFile = null;
      this.packageFileList = [];
      this.$message.info('文件已移除，可以重新上传');
    },
    
    // 批量导入
    handlePackageImport() {
      if (!this.selectedPackageFile) {
        this.$message.warning('请先选择要导入的Excel文件');
        return;
      }
      
      this.packageImportLoading = true;
      this.packageImportProgress = 0;
      this.$message.info('正在导入数据，请稍候...');
      
      // 创建进度更新函数
      const updateProgress = (progressEvent) => {
        if (progressEvent.percent) {
          this.packageImportProgress = Math.round(progressEvent.percent);
        }
      };
      
      importLabelerTaskPackageAPI(this.selectedPackageFile, { onProgress: updateProgress }).then(res => {
        this.packageImportLoading = false;
        // 检查响应数据结构
        console.log('导入结果:', res);
        
        if (res.successRows!==0) {
          // 更新导入结果数据
          const resultData = res || {};
          const importResult = {
            totalRows: resultData.totalRows || 0,
            successRows: resultData.successRows || 0,
            failRows: resultData.failRows || 0,
            errorMessages: resultData.errorMessages || []
          };
          
          // 根据导入结果给出相应提示
          if (importResult.failRows === 0) {
            this.$message.warning(`导入完成！成功导入${importResult.successRows}条数据`);
          } else {
            this.$message.warning(`导入完成！成功${importResult.successRows}条，失败${importResult.failRows}条`);
          }
          
          // 导入成功后刷新列表
          this.getPackageTableData();
          
          // 清空文件选择
          this.selectedPackageFile = null;
          this.packageFileList = [];
        } else {
          this.$message.error(res.message || '导入失败');
        }
      }).catch(error => {
        this.packageImportLoading = false;
        this.$message.error('导入失败，请检查网络或文件格式');
        console.error('导入错误:', error);
      });
    },
    
    // 获取状态标签类型
    getStatusTagType(status) {
      switch (status) {
        case '进行中':
          return 'primary';
        case '已完成':
          return 'success';
        case '已返修':
          return 'warning';
        default:
          return 'info';
      }
    },
    
    // 获取表格数据
    getPackageTableData() {
      this.packageTableLoading = true;
      
      // 构建查询参数
      const params = {
        currentPage: this.packagePagination.currentPage,
        pageSize: this.packagePagination.pageSize
      };
      
      if (this.packageQueryForm.dateRange && this.packageQueryForm.dateRange.length === 2) {
        params.startDate = this.packageQueryForm.dateRange[0];
        params.endDate = this.packageQueryForm.dateRange[1];
      }
      
      if (this.packageQueryForm.labelerName) {
        params.labelerName = this.packageQueryForm.labelerName;
      }
      
      if (this.packageQueryForm.status) {
        params.status = this.packageQueryForm.status;
      }
      
      // 调用后端接口查询数据
      getLabelerTaskPackageListAPI(params).then(res => {
        this.packageTableLoading = false;
        if (res.code === 200) {
          this.packageTableData = res.data.records || [];
          this.packagePagination.total = res.data.total || 0;
          this.packagePagination.currentPage = res.data.currentPage || 1;
          this.packagePagination.pageSize = res.data.pageSize || 10;
        } else {
          this.$message.error(res.message || '查询失败');
        }
      }).catch(error => {
        this.packageTableLoading = false;
        this.$message.error('查询失败，请检查网络');
        console.error('查询错误:', error);
      });
    },
    
    // 编辑
    handleEditPackage(row) {
      this.packageDialogTitle = '编辑记录';
      this.packageFormData = { ...row };
      // 设置默认值
      if (!this.packageFormData.status) {
        this.packageFormData.status = '进行中';
      }
      this.packageDialogVisible = true;
    },
    
    // 删除
    handleDeletePackage(row) {
      this.$confirm('确认删除该条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端删除接口
        deleteLabelerTaskPackageAPI(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getPackageTableData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(error => {
          this.$message.error('删除失败，请检查网络');
          console.error('删除错误:', error);
        });
      }).catch(() => {});
    },
    
    // 分页 - 每页条数改变
    handlePackageSizeChange(val) {
      this.packagePagination.pageSize = val;
      this.packagePagination.currentPage = 1;
      this.getPackageTableData();
    },
    
    // 分页 - 当前页改变
    handlePackageCurrentChange(val) {
      this.packagePagination.currentPage = val;
      this.getPackageTableData();
    },
    
    // 显示新增对话框
    showAddPackageDialog() {
      this.packageDialogTitle = '新增记录';
      this.resetPackageForm();
      this.packageDialogVisible = true;
    },
    
    // 重置表单
    resetPackageForm() {
      this.packageFormData = {
        labelerName: '',
        receiveTime: '',
        account: '',
        taskBatch: '',
        packageId: '',
        deliveryTime: '',
        deliveryBoxCount: 0,
        repairCount: 0,
        finalBoxCount: 0,
        status: '进行中'
      };
      if (this.$refs.packageForm) {
        this.$refs.packageForm.resetFields();
      }
    },
    
    // 提交表单
    handlePackageSubmit() {
      this.$refs.packageForm.validate((valid) => {
        if (valid) {
          this.packageSubmitLoading = true;
          
          // 判断是新增还是编辑
          const isEdit = !!this.packageFormData.id;
          const apiCall = isEdit 
            ? updateLabelerTaskPackageAPI(this.packageFormData.id, this.packageFormData)
            : addLabelerTaskPackageAPI(this.packageFormData);
          
          apiCall.then(res => {
            this.packageSubmitLoading = false;
            if (res.code === 200) {
              this.$message.success(isEdit ? '修改成功' : '新增成功');
              this.packageDialogVisible = false;
              this.resetPackageForm();
              // 刷新列表
              this.getPackageTableData();
            } else {
              this.$message.error(res.message || '操作失败');
            }
          }).catch(error => {
            this.packageSubmitLoading = false;
            this.$message.error('操作失败，请检查网络');
            console.error('提交错误:', error);
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.labeler-daily-output-page {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      color: #333;
    }
  }
  
  .query-area {
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 20px;
    
    .el-form-item {
      margin-right: 15px;
      margin-bottom: 10px;
    }
    
    .el-form-item:last-child {
      margin-right: 0;
    }
  }
  
  .chart-area {
    margin-top: 30px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
    
    h3 {
      margin: 0 0 15px 0;
      font-size: 16px;
      color: #333;
    }
  }
  
  .batch-import-area {
    margin-top: 40px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
    
    .import-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: #333;
    }
    
    .upload-demo {
      width: 100%;
    }
    
    .file-preview {
      margin-top: 15px;
      padding: 15px;
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      
      .preview-header {
        display: flex;
        align-items: center;
        gap: 10px;
        
        i.el-icon-document {
          font-size: 24px;
          color: #67c23a;
        }
        
        .file-name {
          flex: 1;
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .file-size {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .preview-info {
        margin-top: 10px;
        padding: 8px 12px;
        background: #ecf5ff;
        border-left: 3px solid #409eff;
        border-radius: 4px;
        
        p {
          margin: 0;
          font-size: 13px;
          color: #409eff;
          
          i {
            margin-right: 5px;
          }
        }
      }
    }
  }
}
</style>
